<?php

namespace app\api\controller\wanlshop;

use addons\wanlshop\library\Decrypt\weixin\wxBizDataCrypt;
use addons\wanlshop\library\WanlChat\WanlChat;
use addons\wanlshop\library\WanlSdk\Common;
use addons\wanlshop\library\WeixinSdk\Security;
use app\common\controller\Api;
use app\common\library\Sms;

use app\common\model\user\LevelOrder;
use fast\Random;
use fast\Http;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Validate;


//新增 lina start
/**
 * 分销接口
 */
class Distribution extends Api
{
    protected $noNeedLogin = ['phone', 'perfect', 'demo'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }
    /**
     *直推用户列表
     * */
    public function list()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isGet()) {
            $user=$this->auth->getUser();
            if(($user["is_staff"]!=1 && empty($user["level_id"])) || ($user["is_staff"]==1 && empty($user["staff_status"]))) $this->error("您不能进入分销中心");
            $list = model('app\common\model\User')
                ->field("id,nickname,avatar,level_id")
                ->where(['agent_id'=>$this->auth->id])->paginate();
            $this->success('ok', $list);
        }
        $this->error(__('非法请求'));
    }
    /**
     * 佣金明细
     * */
    public function moneyList()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isGet()) {
            $user=$this->auth->getUser();
            $where=["identity"=>$user["identity"]];
            if($this->request->param("type") && $this->request->param("type")==2){
                //区域合伙人--进入佣金明细
                if($user["identity"]!=2) $this->error("您不能查看区域合伙人佣金提现记录");
                $where["identity"]=2;
            }
            if($user["identity"]==2 && (!$this->request->param("type") && $this->request->param("type")!=2)){
                //区域合伙人--分销进入佣金明细
                $where["identity"]=0;
            }
            //if($user["is_staff"]!=1 || $user["staff_status"]!=1) $this->error("您不能查看订单明细");
            $list = model('app\common\model\Distribution')
                ->field("id,order_no,money,status,createtime,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime_text,remark")
                ->where("commiss_user_id = ".$this->auth->id)//." or (agent_id =".$this->auth->id." and identity)"
                ->where($where)
                ->order("createtime","desc")
                ->paginate();
            $this->success('ok', $list);
        }
        $this->error(__('非法请求'));
    }
    /**
     * 佣金提现到余额
     * */
    public function withdrawalToBalance()
    {
        $model=new \app\common\model\User();
        $user=$model->find($this->auth->id);
        if(!$this->request->param("money")) $this->error("请输入提现金额");
        $params = $this->request->param();
        $identity=$user["identity"];
        if($this->request->param("type") && $this->request->param("type")==2){
            //区域合伙人--进入佣金提现记录
            $identity=1;
            if($user["identity"]!=2) $this->error("您不能提现区域合伙人佣金");
            if($user["region_commission"]<=0) $this->error("可提现佣金不足");
            if($params["money"]>$user["region_commission"]) $this->error("可提现金额不足");
        }else{
            if($user["commission"]<=0) $this->error("可提现佣金不足");
            if($params["money"]>$user["commission"]) $this->error("可提现金额不足");
        }
        if($user["identity"]==2 && (!$this->request->param("type") && $this->request->param("type")!=2)){
            //区域合伙人--分销进入佣金提现记录
            $identity=0;
        }
        Db::startTrans();
        try {
            controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$params['money'], $user['id'], '佣金提现到余额', 'withdraw', 1);
            //$ret=$user->save(["commission"=>bcsub($user["commission"],$params["money"],2)]);\
            if($this->request->param("type") && $this->request->param("type")==2){
                //区域合伙人--进入佣金提现记录
                $ret=$model->region_commission(-$params["money"],$user['id'],"佣金提现到余额",0,0,2,0);
            }else{
                $ret=$model->commission(-$params["money"],$user['id'],"佣金提现到余额",0,0,$identity,0);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success(__('提现成功'));
    }
    /**
     * 佣金提现记录
     * */
    public function withdrawalLog()
    {
        $user=$this->auth->getUser();
        $where=["user_id"=>$this->auth->id,"memo"=>"佣金提现到余额","type"=>0,"identity"=>$user["identity"]];//,"service_ids"=>1
        if($this->request->param("type") && $this->request->param("type")==2){
            //区域合伙人--进入佣金提现记录
            $where["identity"]=2;
            if($user["identity"]!=2) $this->error("您不能查看区域合伙人佣金提现记录");
        }
        if($user["identity"]==2 && (!$this->request->param("type") && $this->request->param("type")!=2)){
            //区域合伙人--分销进入佣金提现记录
            $where["identity"]=0;
        }
        $list =model('app\common\model\CommissionLog')
            ->field("id,perk_money money,createtime,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime_text")
            //->where(["user_id"=>$this->auth->id,"type"=>1,"memo"=>"佣金提现到余额"])
            ->where($where)
            ->order("createtime","desc")
            ->paginate();
        $this->success('ok', $list);
    }
    /**
     * 团员订单明细
     * */
    public function orderList()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isGet()) {
            $user=$this->auth->getUser();
            //if($user["is_staff"]!=1) $this->error("您不能查看订单明细");
            if(($user["is_staff"]!=1 && empty($user["level_id"])) || ($user["is_staff"]==1 && empty($user["staff_status"]))) $this->error("您不能进入分销中心");
            $type=$this->request->get("type")??1;
            $orderGoodsModel=new \app\index\model\wanlshop\OrderGoods();
            $levelModel=new LevelOrder();
            /*$list = model('app\common\model\Distribution')
                ->alias("distribution")
                ->field("id,distribution.type,distribution.order_id,order_goods_id,distribution.order_no,distribution.money,distribution.status,distribution.createtime,from_unixtime(distribution.createtime, '%Y-%m-%d %H:%i:%s') createtime_text,
                distribution.remark")
                ->join("user user","user.id=distribution.agent_id or user.id=distribution.commiss_user_id")
                ->with(["payuser"=>function($query){
                    $query->withField('id,nickname,avatar');
                }])
                ->where("commiss_user_id = ".$this->auth->id." or (distribution.agent_id =".$this->auth->id.")")
                ->where(["type"=>$type])
                ->order("distribution.createtime","desc")
                ->paginate()
                ->each(function ($v) use ($orderGoodsModel,$levelModel){
                    if($v["type"]==1){
                        //会员订单
                        $level=$levelModel->field("level_details")->where(["id"=>$v["order_id"]])->find();
                        if(!empty($level)){
                            $level=json_decode($level["level_details"],true);
                            $v["level"]=[
                                "name"=>$level["name"],
                                "price"=>$level["price"],
                            ];
                        }
                    }else{
                        //商品订单
                        $goods=$orderGoodsModel->field("id,title,image,price,number,difference")->where(["id"=>$v["order_goods_id"]])->select();
                        $v["goods"]=$goods;
                    }
                });*/
            $list = model('app\common\model\Distribution')
                ->alias("distribution")
                ->field("id,distribution.type,distribution.order_id,order_goods_id,distribution.order_no,distribution.money,distribution.status,distribution.createtime,from_unixtime(distribution.createtime, '%Y-%m-%d %H:%i:%s') createtime_text,
                distribution.remark")
                ->join("user user","user.id=distribution.agent_id",'left')
                ->with(["payuser"=>function($query){
                    $query->withField('id,nickname,avatar');
                }])
                ->where("distribution.agent_id = ".$this->auth->id)
                ->where(["type"=>$type])
                ->order("distribution.createtime","desc")
                ->group("distribution.order_no")
                ->paginate()
                ->each(function ($v) use ($orderGoodsModel,$levelModel){
                    if($v["type"]==1){
                        //会员订单
                        $level=$levelModel->field("level_details")->where(["order_no"=>$v["order_no"]])->find();
                        if(!empty($level)){
                            $level=json_decode($level["level_details"],true);
                            $v["level"]=[
                                "name"=>$level["name"],
                                "price"=>$level["price"],
                            ];
                        }
                    }else{
                        //商品订单
                        $goods=$orderGoodsModel->field("id,title,image,price,number,difference")->where(["order_id"=>$v["order_id"]])->select();
                        $v["goods"]=$goods;
                    }
                });
            $this->success('ok', $list);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 团长查看团队团员列表
     * */
    public function teamUserList()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isGet()) {
            $user=$this->auth->getUser();
            if($user["identity"]!=1) $this->error("您不能查看团队团员");
            $list = model('app\common\model\User')
                ->field("id,nickname,avatar,level_id")
                ->where("agent_id =".$this->auth->id." or team_id=".$this->auth->id)
                ->paginate();
            $this->success('ok', $list);
        }
        $this->error(__('非法请求'));
    }
}
//新增 lina end